<?php

namespace App\Models;

class Ads extends Base
{
    protected $table = 'ads';

    const STATUS_1 = 1;
    const STATUS_2 = 2;

    const STATUS_TEXT = [
        self::STATUS_1 => '<span class="el-tag">正常</span>',
        self::STATUS_2 => '<span class="el-tag el-tag--danger">锁定</span>',
    ];

    const TARGET_1 = 1;
    const TARGET_2 = 2;

    const TARGET_TEXT = [
        self::TARGET_1 => '<span class="el-tag  el-tag--danger">是</span>',
        self::TARGET_2 => '<span class="el-tag">否</span>',
    ];

    protected $fillable = [
        'id','adsense_id','cate_id','title','link','sort','thumb','status','created_at','updated_at'
    ];

    //连表查询
    public function category(){//分类
        return $this->belongsTo('App\Models\Categorys', 'cate_id', 'id');
    }

    /**
     * 获取列表
     * @param array $params 条件参数
     * @param array $fields 查询的字段
     * @return mixed
     */
    protected function getList($params = [], $fields = ['*'], $limit = 10){
        $lists = $this->select($fields)
            ->where(function ($query) use ($params) {
                if(isset($params['kwd']) && $params['kwd']) {
                    $query ->where('link','like','%' . $params['kwd'] . '%');
                }
                if(isset($params['adsense_id']) && $params['adsense_id']) {
                    $query ->where('adsense_id',$params['adsense_id']);
                }
                if(isset($params['cate_id']) && $params['cate_id']) {
                    $query ->where('cate_id',$params['cate_id']);
                }
                if(isset($params['status']) && $params['status']) {
                    $query ->where('status',$params['status']);
                }
                
            })->where('status','<>',-1)
            ->with(['category' => function ($query) {
                $query->select(['id','name'])->get();
            }])
            ->orderBy('sort', 'asc')
            ->when($params, function ($query) use($params){
                if(isset($params['limit']) && $params['limit']) {
                    return $query->limit($params['limit']);
                }
            })->get();
        $this->stateToText($lists,[
            'status' => self::STATUS_TEXT,
            'target' => self::TARGET_TEXT,
        ]);
        return $lists;
    }

}
